package com.qingdai.evaluatecenter.controller;

import com.qingdai.business.emuns.Address;
import com.qingdai.business.emuns.Commodity;
import com.qingdai.business.emuns.Evaluate;
import com.qingdai.business.emuns.Order;
import com.qingdai.business.entities.CommonResult;
import com.qingdai.business.service.OrderService;
import com.qingdai.business.utils.JwtUtil;
import com.qingdai.business.utils.TimeUtil;
import com.qingdai.business.utils.UUIDUtil;
import com.qingdai.evaluatecenter.repository.EvaluateRepository;
import io.seata.spring.annotation.GlobalTransactional;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@RestController
@RequestMapping("/evaluate")
@Tag(name = "评价")
public class EvaluateController {
    @Resource
    private EvaluateRepository evaluateRepository;
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private UUIDUtil uuidUtil;
    @DubboReference
    private OrderService orderService;
    @Resource
    private TimeUtil timeUtil;

    @GetMapping("/jwt")
    @Operation(summary = "获取本人创建评论", description = "获取本人创建评论")
    @Parameters({
//            @Parameter(name = "id", description = "id", required = true),
    })
    public CommonResult<List<Evaluate>> getEvaluateByJwt(HttpServletRequest request) {
        CommonResult userIdByJwtCommonResult = jwtUtil.getUserIdByRequest(request);
        Integer userIdByJwt = (Integer) userIdByJwtCommonResult.getData();
        Evaluate evaluate = new Evaluate();
        evaluate.setBuyerId(userIdByJwt);
        Example<Evaluate> example = Example.of(evaluate);
        List<Evaluate> allEvaluate = evaluateRepository.findAll(example);
        return new CommonResult<>(200, "获取本人创建评论", allEvaluate);
    }

    @PostMapping("/jwt")
    @GlobalTransactional
    @Operation(summary = "创建新评价", description = "创建新评价")
    @Parameters({
//            @Parameter(name = "id", description = "id", required = true),
            @Parameter(name = "commodityIdList", description = "商品IdList", required = true),
            @Parameter(name = "orderId", description = "订单Id", required = true),
            @Parameter(name = "commodityScoreList", description = "商品评分List", required = true),
            @Parameter(name = "logisticsScore", description = "物流评分", required = true),
            @Parameter(name = "shopScore", description = "店铺评分", required = true),
            @Parameter(name = "detailsList", description = "商品评价内容List", required = true),
    })
    public CommonResult createEvaluateByJwt(@RequestParam(required = true) Integer orderId,
                                            @RequestParam(required = true) String commodityScoreList,
                                            @RequestParam(required = true) Double logisticsScore,
                                            @RequestParam(required = true) Double shopScore,
                                            @RequestParam(required = true) String detailsList,
                                            HttpServletRequest request) {
        CommonResult result = jwtUtil.getUserIdByRequest(request);
        Integer jwtUserId = (Integer) result.getData();
        if (!Objects.equals(orderService.getById(orderId).getBuyerId(), jwtUserId)) {
            return new CommonResult(400, "不具备评价该订单权限");
        }

        Evaluate evaluateExample = new Evaluate();
        evaluateExample.setOrderId(orderId);
        Example<Evaluate> example = Example.of(evaluateExample);
        Optional<Evaluate> evaluateById = evaluateRepository.findOne(example);
        if (evaluateById.isPresent()) {
            return new CommonResult(400, "已评价过该订单");
        }

        Evaluate evaluate = new Evaluate(uuidUtil.getId(), orderId, jwtUserId, commodityScoreList, logisticsScore, shopScore, detailsList);
        try {
            Evaluate insert = evaluateRepository.insert(evaluate);
            if (insert.getId() == null) {
                throw new Exception("创建评价失败");
            }
        } catch (Exception e) {
            return new CommonResult(400, "创建评价失败");
        }
        try {
            boolean saveResult = orderService.save(new Order(orderId, null, null, null, null, null, null, null, null, timeUtil.getNow(), null, null, null, null));
            if (!saveResult) {
                throw new Exception("创建评价失败(订单评价时间更改失败)");
            }
        } catch (Exception e) {
            return new CommonResult(400, "创建评价失败(订单评价时间更改失败)");
        }
        return new CommonResult(200, "创建评价成功");
    }


    @GetMapping("/id")
    @Operation(summary = "根据id获取评价", description = "根据id获取评价")
    @Parameters({
            @Parameter(name = "id", description = "id", required = true),
    })
    public CommonResult getEvaluateById(@RequestParam(required = true) String id, HttpServletRequest request) {
        Optional<Evaluate> evaluate = evaluateRepository.findById(id);
        if (evaluate.isEmpty()) {
            return new CommonResult<>(400, "未找到评价");
        }
        return new CommonResult<>(200, "根据id获取评价成功", evaluate);
    }

    //TODO
    @GetMapping("/orderId")
    @Operation(summary = "根据orderId获取评价", description = "根据orderId获取评价")
    @Parameters({
            @Parameter(name = "orderId", description = "orderId", required = true),
    })
    public CommonResult getEvaluateByOrderId(@RequestParam(required = true) Integer orderId, HttpServletRequest request) {
        Evaluate evaluate = new Evaluate();
        evaluate.setOrderId(orderId);
        Example<Evaluate> example = Example.of(evaluate);
        Optional<Evaluate> evaluateOptional = evaluateRepository.findOne(example);
        if (evaluateOptional.isEmpty()) {
            return new CommonResult<>(400, "根据orderId未找到评价");
        }
        return new CommonResult<>(200, "根据orderId未找到评价", evaluateOptional.get());
    }

    @GetMapping("/shopId")
    @Operation(summary = "根据shopId获取评价", description = "根据shopId获取评价")
    @Parameters({
            @Parameter(name = "shopId", description = "shopId", required = true),
    })
    public CommonResult getEvaluateByShopId(@RequestParam(required = true) Integer shopId, HttpServletRequest request) {
        List<Order> orderByShopId = orderService.getOrderByShopId(shopId);
        List<Evaluate> evaluates = new ArrayList<>();
        for (int i = 0; i < orderByShopId.size(); i++) {
            Integer orderId = orderByShopId.get(i).getId();
            System.out.println(orderId);
            Evaluate evaluate = new Evaluate();
            evaluate.setOrderId(orderId);
            Example<Evaluate> example = Example.of(evaluate);
            Optional<Evaluate> evaluateById = evaluateRepository.findOne(example);
            evaluateById.ifPresent(evaluates::add);
        }
        if (evaluates.isEmpty()) {
            return new CommonResult<>(400, "根据shopId未找到评价");
        }
        return new CommonResult<>(200, "根据shopId获取评价成功", evaluates);
    }

    @PutMapping("/jwt/id")
    @Operation(summary = "根据id更改评价", description = "根据id更改评价")
    @Parameters({@Parameter(name = "id", description = "id", required = true),
            @Parameter(name = "commodityIdList", description = "商品IdList", required = false),
            @Parameter(name = "orderId", description = "订单Id", required = false),
            @Parameter(name = "commodityScoreList", description = "商品评分List", required = false),
            @Parameter(name = "logisticsScore", description = "物流评分", required = false),
            @Parameter(name = "shopScore", description = "店铺评分", required = false),
            @Parameter(name = "detailsList", description = "商品评价内容List", required = false),

    })
    public CommonResult updateEvaluateByIdAndJwt(@RequestParam(required = true) String id,
                                                 @RequestParam(required = false) Integer orderId,
                                                 @RequestParam(required = false) String commodityScoreList,
                                                 @RequestParam(required = false) Double logisticsScore,
                                                 @RequestParam(required = false) Double shopScore,
                                                 @RequestParam(required = false) String detailsList,
                                                 HttpServletRequest request) {
        CommonResult result = jwtUtil.getUserIdByRequest(request);
        Integer jwtUserId = (Integer) result.getData();
        Optional<Evaluate> evaluate = evaluateRepository.findById(id);
        if (evaluate.isEmpty()) {
            return new CommonResult(400, "id非法");
        }
        if (!Objects.equals(evaluate.get().getBuyerId(), jwtUserId)) {
            return new CommonResult(400, "请勿修改他人评价");
        }
        Evaluate save = evaluateRepository.save(new Evaluate(id, orderId, jwtUserId, commodityScoreList, logisticsScore, shopScore, detailsList));
        if (save.getId() == null) {
            return new CommonResult(400, "修改评价失败");
        }
        return new CommonResult(200, "修改评价成功");
    }


    @DeleteMapping("/jwt/id")
    @GlobalTransactional
    @Operation(summary = "根据id删除评价", description = "根据id删除评价")
    @Parameters({
            @Parameter(name = "id", description = "id", required = true),
    })
    public CommonResult deleteEvaluateByIdAndJwt(@RequestParam(required = true) String id,
                                                 HttpServletRequest request) {
        CommonResult result = jwtUtil.getUserIdByRequest(request);
        Integer jwtUserId = (Integer) result.getData();
        Optional<Evaluate> evaluate = evaluateRepository.findById(id);
        if (evaluate.isEmpty()) {
            return new CommonResult(400, "id非法");
        }
        if (!Objects.equals(evaluate.get().getBuyerId(), jwtUserId)) {
            return new CommonResult(400, "请勿删除他人评价");
        }
        evaluateRepository.deleteById(id);
        return new CommonResult(200, "删除评价成功");
    }


}
